# coding=utf-8
# import time
from django.shortcuts import redirect
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
# from c21_qrcode.common import common
from c21_qrcode.utils import viewutils
from c21_qrcode.common.redis_service import SLurl, ScanCensus
from c21_qrcode.common.auth import auth_check


class UrlRender(APIView):
    '''
        短链跳转
    '''

    def get(self, request, short_url):
        slurl = SLurl()
        res = slurl.get(short_url)
        if not res:
            raise Http404
        long_url = res['long_url']
        # 统计二维码扫描数
        scan_census = ScanCensus()
        scan_census.add_scan_num(short_url)
        return redirect(long_url)


class GetQrcode(APIView):

    # @auth_check
    def post(self, request):
        avatar_url = request.data.get('avatar_url')
        url = request.data.get('url')
        appid = request.data.get('appid')
        qrcode_info = viewutils.get_qrcode_info(
            url, str(appid), avatar_url, need_icon=1)
        if qrcode_info is False:
            return Response({
                'status': 500,
                'msg': 'server error'})
        context = {
            "status": 200,
            "data": {
                "qrcode_url": qrcode_info['qrcode_url'],
                "short_url": qrcode_info['short_url']
            }
        }
        return Response(context)


class QrcodeScanNum(APIView):
    # @auth_check
    def post(self, request):
        short = request.data.get('short', None)
        shorts = request.data.get('shorts', [])
        if short:
            qrcode_scan_num = ScanCensus().get_scan_num(short)
            context = {
                'status': 200,
                'data': {
                    'qrcode_scan_num': qrcode_scan_num
                }
            }
            return Response(context)
        else:
            shorts = shorts.split(',')
            qrcode_scan_num = ScanCensus().mget_scan_num(shorts)
            context = {
                'status': 200,
                'data': {
                    'qrcode_scan_nums': dict(
                        zip(shorts, qrcode_scan_num))
                }
            }
            return Response(context)
